<template>
  <div class="direct-plan-add-view view-container">

    <header-module
      left-custom
      padding
    >
      <template #left-con>
        <div>
          <span style="font-size: 16px; margin-right: 20px">新建终端直销规划</span>
        </div>
      </template>

      <template #btn>
        <el-button
          class="main-btn"
          size="small"
          @click="onBack"
        >返回</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="onSave"
        >保存</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="onAudit"
        >提交审核</el-button>
      </template>

    </header-module>

    <div class="main-content">

      <item-title title="基本信息" />

      <el-form
        ref="ruleForm"
        :inline="true"
        :model="datas"
        :rules="rules"
        class="filter-form-inline"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row :gutter="20">

          <el-col :span="8">
            <el-form-item
              label="关联市场准入"
              style="width: 100%"
            >

              <el-input
                ref="refInput"
                v-model="datas.selectName"
                :disabled="list.length > 0"
                placeholder="请输入市场准入"
                clearable
                @clear="chanceClear"
                @blur="chanceBlur"
                @focus="chanceFocus"
              />

            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="规划名称"
              prop="planName"
              style="width: 100%"
            >
              <el-input
                v-model="datas.planName"
                clearable
                placeholder="请输入规划名称"
                @blur="nameBlur"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="规划地区"
              prop="areas"
              style="width: 100%"
            >
              <el-cascader
                ref="cascader"
                v-model="datas.areas"
                style="width: 100%"
                :disabled="list.length > 0"
                :options="citys"
                :popper-append-to-body="false"
                :props="props1"
                collapse-tags
                placeholder="请选择地区"
                @change="areaChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="产品通用名"
              prop="productPopularName"
              style="width: 100%"
            >

              <product-popover
                :disabled="disabled || changeChance"
                :searchs="datas.productPopularName"
                type="3"
                @confirm="productConfirm"
              >
                <el-input
                  v-model="datas.productPopularName"
                  :disabled="datas.chanceId > 0"
                  placeholder="请输入产品名称"
                />
              </product-popover>

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="商品名"
              style="width: 100%"
            >
              <el-input
                v-model="datas.productName"
                disabled
                placeholder="请选择商品名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="包装规格"
              style="width: 100%"
            >
              <el-input
                v-model="datas.packSpecs"
                disabled
                placeholder="请选择包装规格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="生产厂家"
              style="width: 100%"
            >
              <el-input
                v-model="datas.producer"
                disabled
                placeholder="请选择生产厂家"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="终端价"
              prop="terminalPrice"
              style="width: 100%"
            >
              <app-price-popover
                ref="pricePop"
                :props-product="datas"
                @confirm="priceConfirm"
              >

                <div style="display:flex;justify-content: flex-start">
                  <el-select
                    v-model="datas.terminalPrice"
                    :disabled="!datas.productId || !datas.region || !datas.region.length"
                    placeholder="请选择终端价"
                    style="width: 100%"
                    @focus="priceFocus"
                  >
                    <template #empty />
                  </el-select>

                  <div
                    v-if="datas.sellUnit"
                    style="margin-left: 10px;min-width: 50px"
                  >
                    元/{{ getLabel('sell_unit', datas.sellUnit) }}
                  </div>
                  <div
                    v-else
                    style="margin-left: 10px"
                  >元</div>
                </div>
              </app-price-popover>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="规划结束日期"
              prop="expireTime"
              style="width: 100%"
            >
              <date-picker
                v-model:date="datas.expireTime"
                :disabled-date="disabledDate"
                placeholder="请选择结束日期"
                style="width: 100%"
                @change="dateChange"
              />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <!--
      <el-form
        :model="datas"
        class="filter-form-inline"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="其他描述">
              <el-input
                v-model="datas.remark"
                :rows="2"
                placeholder="请输入其他描述"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="相关附件">
              <upload-file-view
                :file-arr="datas.files"
                is-upload
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      -->
      <item-title title="招商地区明细" />

      <areaView
        v-model:list="list"
        :area="areaList"
        :datas="datas"
        :deletes="deletes"
      />

    </div>

    <chanceDialog
      ref="chanceDialog"
      type="3"
      @confirm="chanceConfirm"
    />

  </div>
</template>

<script>
import chanceDialog from '../../modules/chanceDialog'
import { getScreenAreaData } from '../../../../../../utils/areaFuc'
import area from '@/utils/area'
import { useRoute, useRouter } from 'vue-router'
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from 'vue'

export default defineComponent({
  name: 'Index',
  components: {
    areaView: defineAsyncComponent(() => import('./modules/areaView.vue')),
    chanceDialog,
  },
  setup() {
    const currentInstance = getCurrentInstance()
    const route = useRoute()
    const router = useRouter()
    const api = inject('api')
    const rules = ref({
      planName: [
        {
          required: true,
          message: '请输入规划名称',
          trigger: 'blur',
        },
      ],
      productPopularName: [
        {
          required: true,
          message: '请选择产品',
          trigger: 'blur',
        },
      ],
      expireTime: [
        {
          type: 'date',
          required: true,
          message: '请选择结束日期',
          trigger: 'change',
        },
      ],
      areas: [
        {
          required: true,
          message: '请选择地区',
          trigger: 'change',
        },
      ],
      terminalPrice: [
        {
          required: true,
          message: '请选择终端价',
          trigger: 'change',
        },
      ],
    })
    const props1 = reactive({
      expandTrigger: 'hover',
      label: 'regionName',
      value: 'regionCode',
    })

    var data = reactive({
      datas: {
        terminalPrice: '',
        productPriceId: 0,
        accessMode: '',
        areas: '',
        region: [],
        planType: '3',
        date: '',
        remark: '',
        chanceId: 0,
        chanceName: '',
        selectName: '',
        planName: '',
        expireTime: '',
        productId: 0,
        productName: '',
        packSpecs: '',
        approvalNumber: '',
        productPopularName: '',
        sellUnit: '',
        files: [],
      },
      list: [],
      disabled: true,
      ChanceInfo: {},
      ruleForm: null,
      deletes: [],
      citys: [],
      chancePop: null,
      changeChance: false,
      chanceDialog: null,
      refInput: null,
      pricePop: null,
      areaOptions: {},
      areaList: [],
    })

    const onBack = () => {
      router.back()
    }

    const areaChange = (val) => {
      for (let i = 0; i < data.citys.length; i++) {
        if (data.citys[i].regionCode == val[0]) {
          const index = data.citys[i].children.findIndex(
            (a) => a.regionCode == val[1]
          )
          if (index != -1) {
            data.datas.region = [data.citys[i].children[index]]

            data.areaList = data.areaOptions[data.datas.region[0].regionCode]
          }
        }
      }
    }

    const getArea = (list) => {
      const arr = []
      list.forEach((a) => {
        const b = JSON.parse(JSON.stringify(a))
        b.children.forEach((city) => {
          if (city.children) {
            data.areaOptions[city.regionCode] = [...city.children]
          }

          city.children = null
        })
        arr.push(b)
      })
      return arr
    }

    const priceConfirm = (val) => {
      data.datas.productPriceId = val.id
      data.datas.terminalPrice = Number(val.terminalPrice)
      data.datas.accessMode = val.accessMode
    }

    const priceFocus = (val) => {
      if (!data.datas.productId) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择产品',
        })
        return
      }
      if (!data.datas.region || !data.datas.region.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择规划地区',
        })
        return
      }
      data.pricePop.openPopover()
    }

    const chanceBlur = () => {
      if (!data.datas.selectName) {
        data.datas.chanceId = 0
        data.datas.chanceName = ''
        data.citys = getArea(area)
      }
      if (data.datas.chanceName) {
        data.datas.selectName = data.datas.chanceName
      }
      // data.chancePop.openPopover()
    }

    const chanceClear = () => {
      data.citys = getArea(area)
      data.datas.chanceId = 0
      data.datas.chanceName = ''
      data.datas.selectName = ''
      data.datas.chanceRegion = []
    }

    const chanceFocus = () => {
      // data.chancePop.openPopover()
      data.chanceDialog.openDialog()
      data.refInput.blur()
    }

    const chanceConfirm = (item) => {
      data.changeChance = true
      data.datas.chanceId = item.id
      data.datas.chanceName = item.chanceName
      data.datas.selectName = item.chanceName
      data.datas.chanceRegion = item.region
      data.datas.expireTime = item.expireTime

      data.datas.productId = item.productId
      data.datas.productName = item.productName
      data.datas.productPopularName = item.productPopularName
      data.datas.packSpecs = item.packSpecs
      data.datas.producer = item.producer
      data.datas.approvalNumber = item.approvalNumber
      data.datas.sellUnit = item.sellUnit
      data.datas.region = []
      data.datas.areas = []
      data.citys = getArea(getScreenAreaData(item.region))

      setTimeout(() => {
        data.changeChance = false
      }, 500)
    }

    const onAudit = () => {
      if (checkData()) {
        currentInstance.proxy
          .alertBox({
            message: '是否提交审核该规划？',
            title: '审核',
          })
          .then(() => {
            saveData()
              .then(() => {
                audit()
              })
              .catch((err) => {
                audit()
              })
          })
          .catch((err) => {
            console.log(err)
          })
      }
    }

    const audit = () => {
      api.plan.PLAN_CHECK_COMMIT({ id: data.datas.id }).then((res) => {
        if (res.code) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        } else {
          currentInstance.proxy.customMessage({
            type: 'success',
            message: '提交成功',
          })
          router.back()
        }
      })
    }

    const onSave = () => {
      if (checkData()) {
        saveData()
          .then(() => {
            getData(data.datas.id)
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '保存成功',
            })
          })
          .catch((err) => {
            if (err) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: err,
              })
            }
          })
      }
    }

    const saveData = () => {
      return new Promise((resolve, reject) => {
        const postData = {
          planInfo: { ...data.datas },
          planDetail: data.list,
          deleteDetailIds: data.deletes,
        }

        if (route.query.id || data.datas.id) {
          api.plan
            .PLAN_EDIT(postData)
            .then((res) => {
              if (!res.code) {
                resolve()
              } else {
                reject(res.msg)
              }
            })
            .catch((err) => {
              reject()
            })
        } else {
          api.plan
            .PLAN_CREATE(postData)
            .then((res) => {
              if (!res.code) {
                data.datas.id = res.data.plan.id
                resolve()
              } else {
                reject(res.msg)
              }
            })
            .catch((err) => {
              reject()
            })
        }
      })
    }

    const checkData = () => {
      let bo
      data.ruleForm.validate((value) => {
        if (value) {
          if (!data.datas.productId) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请选择产品',
            })
            bo = false
            return
          }
          if (data.list.length) {
            for (let i = 0; i < data.list.length; i++) {
              const a = data.list[i]

              if (!a.name && !a.streetCode) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: '请完善序号' + (i + 1) + '规划招商地区',
                })
                bo = false
                return
              }
              if (!a.devTerminalNum) {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: '请完善序号' + (i + 1) + '终端开发数量',
                })
                bo = false
                return
              }
            }
          }
          bo = true
        } else {
          bo = false
        }
      })
      return bo
    }

    const getData = (id) => {
      api.plan.GET_PLAN_DETAIL({ id: id }).then((res) => {
        if (!res.code) {
          data.deletes = []
          data.datas = res.data.plan.planInfo
          data.datas.selectName = data.datas.chanceName
          data.datas.areas = [
            data.datas.region[0].parentId + '',
            data.datas.region[0].regionCode,
          ]
          console.log(data.datas.areas)
          if (res.data.plan.planDetail) {
            data.list = res.data.plan.planDetail
          }
          if (data.datas.chanceId) {
            data.citys = getArea(getScreenAreaData(data.datas.chanceRegion))
          } else {
            data.citys = getArea(area)
          }
          data.list.forEach((a) => {
            a.area = []
            if (a.areaCode) {
              a.area.push(a.areaCode)
            }
            if (a.streetCode) {
              a.area.push(a.streetCode)
            }
            a.name = a.streetName ? a.areaName + '/' + a.streetName : a.areaName
          })
          data.areaList = data.areaOptions[data.datas.region[0].regionCode]
          setTimeout(() => {
            data.disabled = false
          }, 100)
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }

    const getChanceData = () => {
      api.chance.CHANCE_DETAIL(route.query.chance_id).then((res) => {
        if (!res.code && res.data) {
          data.ChanceInfo = res.data.ChanceInfo

          data.datas.chanceId = data.ChanceInfo.id
          data.datas.chanceName = data.ChanceInfo.chanceName
          data.datas.chanceRegion = data.ChanceInfo.region
          data.datas.expireTime = data.ChanceInfo.expireTime

          data.datas.productId = data.ChanceInfo.productId
          data.datas.productName = data.ChanceInfo.productName
          data.datas.productPopularName = data.ChanceInfo.productPopularName
          data.datas.packSpecs = data.ChanceInfo.packSpecs
          data.datas.approvalNumber = data.ChanceInfo.approvalNumber
          data.datas.sellUnit = data.ChanceInfo.sellUnit

          data.citys = getScreenAreaData(data.ChanceInfo.region)
        }

        setTimeout(() => {
          data.disabled = false
        }, 100)
      })
    }

    const dateChange = (val) => {}

    const productConfirm = (val) => {
      data.datas.productId = val.id
      data.datas.productPopularName = val.productPopularName
      data.datas.productName = val.productName
      data.datas.approvalNumber = val.approvalNumber
      data.datas.packSpecs = val.packSpecs
      data.datas.producer = val.producer
      data.datas.sellUnit = val.sellUnit
    }

    const nameBlur = () => {
      if (data.datas.planName) {
        const pam = {
          table: 'plan_info',
          column: 'plan_name',
          column_data: data.datas.planName,
          id: data.datas.id ? data.datas.id : 0,
        }
        api.common.COMMON_CHECK_UNIQUE(pam).then((res) => {
          if (!res.code && res.data) {
            if (res.data.exist !== '0') {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: '名称已重复，请重新输入',
              })
            }
          }
        })
      }
    }

    const disabledDate = (time) => {
      return !(time.getTime() > Date.now())
    }

    onMounted(() => {
      if (route.query.id) {
        getData(route.query.id)
      } else if (route.query.chance_id) {
        getChanceData()
      } else {
        data.disabled = false
        data.citys = getArea(area)
      }
    })

    return {
      ...toRefs(data),
      rules,
      props1,

      disabledDate,
      onBack,
      onSave,
      onAudit,
      nameBlur,
      dateChange,
      productConfirm,
      chanceBlur,
      chanceFocus,
      chanceConfirm,
      areaChange,
      priceConfirm,
      priceFocus,
      chanceClear,
    }
  },
})
</script>

<style scoped>
</style>
